import React, { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Input } from 'antd-mobile';
import type { InputRef } from 'antd-mobile/es/components/input';
import type { AIMessage } from '../../services/xfAi';
import { getAIResponseStream } from '../../services/xfAi';
import './Ai.css';

// 打字机效果的自定义Hook
const useTypewriter = (text: string, speed: number = 30) => {
  const [displayText, setDisplayText] = useState('');
  const [isComplete, setIsComplete] = useState(false);

  useEffect(() => {
    let i = 0;
    setIsComplete(false);
    setDisplayText('');

    const timer = setInterval(() => {
      if (i < text.length) {
        setDisplayText(prev => prev + text[i]);
        i++;
      } else {
        setIsComplete(true);
        clearInterval(timer);
      }
    }, speed);

    return () => clearInterval(timer);
  }, [text, speed]);

  return { displayText, isComplete };
};

// 思考中动画组件
const TypingIndicator = () => (
  <div className="typing-indicator">
    <div className="typing-dot" />
    <div className="typing-dot" />
    <div className="typing-dot" />
  </div>
);

export default function Ai() {
  const navigate = useNavigate();
  const [messages, setMessages] = useState<AIMessage[]>([
    {
      role: 'assistant',
      content: '你好！我是AI助手，很高兴为您服务。请问有什么我可以帮您的吗？'
    }
  ]);
  const [inputValue, setInputValue] = useState('');
  const [isTyping, setIsTyping] = useState(false);
  const chatContainerRef = useRef<HTMLDivElement>(null);
  const [currentTypingIndex, setCurrentTypingIndex] = useState<number | null>(null);
  const inputRef = useRef<InputRef>(null);

  // 自动滚动到底部
  useEffect(() => {
    if (chatContainerRef.current) {
      const scrollContainer = chatContainerRef.current;
      const scrollToBottom = () => {
        scrollContainer.scrollTop = scrollContainer.scrollHeight;
      };
      
      // 使用 requestAnimationFrame 确保在DOM更新后滚动
      requestAnimationFrame(scrollToBottom);
    }
  }, [messages]);

  // 自动聚焦输入框
  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.focus();
    }
  }, []);

  // 处理输入框高度自适应
  const handleInputChange = (value: string) => {
    setInputValue(value);
    if (inputRef.current?.nativeElement) {
      const element = inputRef.current.nativeElement;
      element.style.height = 'auto';
      element.style.height = `${element.scrollHeight}px`;
    }
  };

  // 发送消息
  const handleSend = async () => {
    if (!inputValue.trim() || isTyping) {
      return;
    }

    const userMessage: AIMessage = {
      role: 'user',
      content: inputValue.trim()
    };

    setMessages(prev => [...prev, userMessage]);
    setInputValue('');
    setIsTyping(true);

    // 重置输入框高度
    if (inputRef.current?.nativeElement) {
      inputRef.current.nativeElement.style.height = 'auto';
    }

    try {
      // 添加一个空的AI回复消息
      setMessages(prev => {
        const newMessages = [...prev, { role: 'assistant' as const, content: '' }];
        setCurrentTypingIndex(newMessages.length - 1);
        return newMessages;
      });
      
      await getAIResponseStream(
        messages.concat(userMessage),
        (text) => {
          // 实时更新AI回复
          setMessages(prev => {
            const updated = [...prev];
            updated[updated.length - 1] = { role: 'assistant', content: text };
            return updated;
          });
        },
        () => {
          setIsTyping(false);
          setCurrentTypingIndex(null);
          // 消息发送完成后自动聚焦输入框
          if (inputRef.current) {
            inputRef.current.focus();
          }
        },
        (error) => {
          console.error('AI服务错误:', error);
          setMessages(prev => {
            const updated = [...prev];
            updated[updated.length - 1] = { 
              role: 'assistant', 
              content: '抱歉，我遇到了一些问题：' + error.message
            };
            return updated;
          });
          setIsTyping(false);
          setCurrentTypingIndex(null);
        }
      );
    } catch (error) {
      console.error('发送消息失败:', error);
      setMessages(prev => {
        const updated = [...prev];
        updated[updated.length - 1] = { 
          role: 'assistant', 
          content: '抱歉，我遇到了一些问题，请稍后再试。' 
        };
        return updated;
      });
      setIsTyping(false);
      setCurrentTypingIndex(null);
    }
  };

  // 获取用户头像
  const userAvatar = localStorage.getItem('userAvatar') || 'https://placekitten.com/100/100';

  return (
    <div className="ai-container">
      {/* 顶部导航 */}
      <div className="ai-header">
        <div className="back-button" onClick={() => navigate(-1)}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
            <path d="M15 19L8 12L15 5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
        <div className="header-title">AI助手</div>
        <div className="header-right">
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <circle cx="12" cy="12" r="1" />
            <circle cx="12" cy="5" r="1" />
            <circle cx="12" cy="19" r="1" />
          </svg>
        </div>
      </div>

      {/* 聊天区域 */}
      <div className="chat-container" ref={chatContainerRef}>
        {messages.map((message, index) => (
          <div key={index} className={`message-wrapper ${message.role}`}>
            <div className="message-content">
              {message.content}
              {message.role === 'user' && (
                <div 
                  className="user-avatar"
                  style={{ backgroundImage: `url(${userAvatar})` }}
                />
              )}
            </div>
          </div>
        ))}
        {isTyping && currentTypingIndex === messages.length - 1 && (
          <div className="message-wrapper ai">
            <TypingIndicator />
          </div>
        )}
      </div>

      {/* 底部输入区域 */}
      <div className="input-container">
        <div className="input-wrapper">
          <Input
            ref={inputRef}
            className="message-input"
            placeholder="输入消息..."
            value={inputValue}
            onChange={handleInputChange}
            onEnterPress={handleSend}
            disabled={isTyping}
          />
        </div>
        <button 
          className="send-button" 
          onClick={handleSend}
          disabled={isTyping || !inputValue.trim()}
        >
          {isTyping ? '发送中...' : '发送'}
        </button>
      </div>
    </div>
  );
}
